import React from 'react'
import './discoverVideo.less'
import { useRef, useState } from "react";
import { postList } from '../../../api/index'
import * as uuid from 'uuid'
import { Popup, NavBar } from 'react-vant';
export default function DiscoverVideo(props) {
    const video = useRef();
    const img = useRef();
    const preview = useRef();
    const [state, showState] = useState(true);
    const [stateimg, showImg] = useState();
    const [text, showText] = useState();
    const [showPopup, setShowPopup] = useState(false);
    const [videoState, setVideoState] = useState(true)
    const [dataChunks, setdataChunks] = useState([])
    const [recorderShow, setrecorder] = useState()
    const [stateVideo, setstateVideo] = useState()
    const [stateVideoBalb, setstateVideoBalb] = useState()
    React.useEffect(() => {
        if (videoState) {
            begin()
        }

    }, [])
function   begin(){
    setdataChunks([])
    setstateVideoBalb()
    setstateVideo()
    navigator.mediaDevices
    .getUserMedia({
        audio: true,
        video: true,
    }).then((stream) => {
        video.current.srcObject = stream;

    })
}
    // 开始录制
    function startRecording(stream, lengthInMS) {
  
        let recorder = new MediaRecorder(stream);
        let arr = JSON.parse(JSON.stringify(dataChunks))

        recorder.ondataavailable = (event) => {
            let data = event.data;
            arr.push(data)
            setdataChunks([...arr])
        };
        recorder.start(1000);
        setrecorder(recorder)
    }
    return (
        <div className='videos'>
            <div className='top'>
                {
                    state ? (
                        <svg className="icon icon-zuojiantou" aria-hidden="true" onClick={() => { props.setvisible() }}><use xlinkHref='#icon-zuojiantou'></use></svg>
                    ) : (
                        <>
                            <svg className="icon icon-zuojiantou" aria-hidden="true" onClick={() => {
                                showState(!state)
                                preview.current.classList.remove('hide')
                                video.current.classList.remove('hides')
                                preview.current.classList.add('hides')
                                video.current.classList.add('hide')
                                console.log( video.current.className);

                                setVideoState(true)
                                    begin()
                            }}
                            ><use xlinkHref='#icon-fanhui'></use></svg>
                            <span onClick={() => { setShowPopup(true) }}>确定</span>
                        </>    
                    )
                }
            </div>
            <video id="recording" ref={video} className="hide" autoPlay='autoPlay' muted={true} muted  > </video>
            <video id="www" ref={preview} className="hides" autoPlay='autoPlay' muted={true} > </video>
            {
                state ? <p className='clickImg'
                    onTouchStart={() => {                      
                        preview.current.classList.remove('hide')
                        video.current.classList.remove('hides')
                        preview.current.classList.add('hides')
                        video.current.classList.add('hide')
                        startRecording(video.current.captureStream())
                    }} onTouchEnd={() => {
                        setVideoState(false)
                        showState(false)
                        preview.current.classList.remove('hides')
                        preview.current.classList.add('hide')
                        video.current.classList.remove('hide')
                        video.current.classList.add('hides')
                        video.current.srcObject.getTracks().forEach((track) => track.stop());
                        recorderShow.stop();
                        let recordedBlob = new Blob(dataChunks, { type: "video/mp4" });
                        if (preview.current) {
                            setstateVideo(recordedBlob)
                            setstateVideoBalb(URL.createObjectURL(recordedBlob))
                            preview.current.src = URL.createObjectURL(recordedBlob);
                        }
                    }}>
                    <span ></span>
                </p> : ''
            }
            <Popup
                className='video-move'
                visible={showPopup}
                onClose={() => setShowPopup(false)}
                style={{ width: '100%', height: '100%' }}
            >
                <NavBar
                    leftArrow
                    rightText="确定"
                    onClickLeft={() => props.setvisible()}
                    onClickRight={() =>{
                        let files = new window.File([stateVideo], { type: stateVideo.type })
                        let nums = Math.ceil(files.size / 10240)
                        let name = uuid.v1()
                        let user=JSON.parse(localStorage.getItem('token'))
                    console.log(files);
                        for (let i = 0; i < nums; i++) {
                            let start = i * 10240
                            let end = i < (nums - 1) ? ((i + 1) * 10240) : files.size
                            let formData = new FormData()
                            formData.set('file', stateVideo.slice(start, end))
                            formData.set('num', i)
                            formData.set('max', nums)
                            formData.set('filename', name)
                            formData.set('text', text)
                            formData.set('info_id', user.info_id)
                            formData.set('xing', user.name)
                            postList('/zbf/video', formData).then(res => {
                                if(Object.getOwnPropertyNames(res.data)!=0){
                                    props.setvisible(res.data)
                                }
                            })
                        }
                    }}
                />

                <textarea type="text" placeholder='你这一刻的想法...' onChange={(e)=>{
                    showText(e.target.value)
                }} />
                <video src={stateVideoBalb }  autoPlay='autoPlay' muted={true} loop ></video>
            </Popup>

        </div>
    )
}

